package LC;

/**
 * @author lhn
 * @date 2024-09-17 15:00
 * 最长回文子串
 */

public class LongestPalindromicSubstring {
    public static void main(String[] args) {
//        String s1 = "babad";
//        System.out.println(longestPalindrome(s1));
//
//        String s2 = "cbbd";
//        System.out.println(longestPalindrome(s2));

        String s3 = "aacabdkacaa";
        System.out.println(longestPalindrome(s3));
    }

    public static String longestPalindrome(String s) {
        int len = s.length();
        if (len < 2) return s;
        int start = 0;
        int end = 0;

        for (int i = 0; i < s.length(); i++) {
            int len1 = expandAroundCenter(s, i, i); // 奇数长度
            int len2 = expandAroundCenter(s, i, i + 1); // 偶数长度
            int lenMax = Math.max(len1, len2);
            if (lenMax > end - start) {
                start = i - (lenMax - 1) / 2;
                end = i + lenMax / 2;
            }
        }

        return s.substring(start, end + 1);
    }

    /**
    * 向两边扩展
    * @author lihaonan
    * @date 2024/9/17 15:55
     * @param s
     * @param left
     * @param right
     * @return int
    */
    public static int expandAroundCenter(String s, int left, int right) {
        // 判断是否为回文串
        while (left >= 0 && right < s.length() &&
            s.charAt(left) == s.charAt(right)
        ) {
            left --;
            right ++;
        }

        return right - left - 1;    // left也包括了，所以要减一
    }

}
